import { useState, useEffect } from 'react'
import { View, Text, Button, Input } from '@tarojs/components'
import { Toast } from '@taroify/core'
import { ArrowUp, ArrowDown, Share } from '@taroify/icons'
import Taro, { useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import './index.scss'

// 获取当前主题
const getCurrentTheme = () => {
  try {
    const savedTheme = Taro.getStorageSync('user-theme-preference')
    if (savedTheme && (savedTheme === 'mint' || savedTheme === 'cream')) {
      return savedTheme
    }
    return 'mint' // 默认主题
  } catch (e) {
    console.error('获取主题失败', e)
    return 'mint' // 出错时返回默认主题
  }
}

// 健身减肥建议数据
const healthAdviceData = {
  Underweight: {
    description: 'BMI < 18.5，偏瘦人群需增重并增强肌肉。',
    diet: [
      '每天增加300–500大卡热量摄入，选择坚果、全脂奶制品、高脂鱼类等高能量食物。',
      '主食以粗粮为主，增加优质蛋白质（蛋类、瘦肉、鱼虾）摄入。'
    ],
    exercise: [
      '每周进行3–4次力量训练（哑铃深蹲、卧推、硬拉），每次45–60分钟。',
      '训练后立即补充蛋白质（乳清蛋白或水果酸奶）。'
    ],
    weeklyActivity: '每周至少3次，每次30分钟以上的中等强度有氧（快走、慢跑）。',
    notes: '避免高强度有氧造成额外消耗；保证充足睡眠促进肌肉恢复。'
  },
  Normal: {
    description: 'BMI 18.5–24.9，正常体重，注重保持与健康管理。',
    diet: ['均衡膳食，每餐八分饱，蔬菜占餐盘一半。', '少吃高糖高脂食物，适量坚果与优质蛋白。'],
    exercise: [
      '每周150分钟中等强度有氧（快走、游泳、骑行）或75分钟高强度有氧。',
      '每周至少2次全身力量训练（俯卧撑、深蹲、平板支撑）。'
    ],
    weeklyActivity: '建议每周5天，每天30分钟中等强度运动。',
    notes: '可通过间歇训练（HIIT）提高心肺功能。'
  },
  Overweight: {
    description: 'BMI 25.0–29.9，超重人群需适度减脂与增强体能。',
    diet: [
      '每日热量赤字300–500大卡，控制碳水摄入，增加膳食纤维（粗粮、蔬菜）。',
      '优选低脂蛋白，如鸡胸肉、鱼肉、豆制品。'
    ],
    exercise: [
      '每周至少300分钟中等强度有氧或150分钟高强度运动。',
      '结合全身力量训练，每周2–3次（俯卧撑、深蹲、哑铃划船）。'
    ],
    weeklyActivity: '每周5–6天，每次30–60分钟中等或高强度运动。',
    notes: '监测心率保持在目标区间；避免长时间静坐，积极活动。'
  },
  Obese: {
    description: 'BMI ≥ 30，肥胖人群需医学指导并稳健减重。',
    diet: [
      '在专业人士指导下设定减脂目标，每日热量摄入控制在1200–1500大卡。',
      '采取小餐多餐模式，保证蛋白质充足，减少精制糖。'
    ],
    exercise: [
      '从低强度有氧（快走、椭圆机）开始，每周150分钟，逐步过渡至中高强度。',
      '力量训练以自重练习为主，循序渐进增加阻力。'
    ],
    weeklyActivity: '每周至少5天，每次30–45分钟，结合有氧+力量。',
    notes: '如有慢性病或心血管疾病，务必先咨询医生再开展运动。'
  }
}

const BmiCalculator = () => {
  // 状态管理
  const [gender, setGender] = useState('male') // 'male' 或 'female'
  const [age, setAge] = useState('')
  const [height, setHeight] = useState('')
  const [weight, setWeight] = useState('')
  const [showResults, setShowResults] = useState(false)
  const [currentBmi, setCurrentBmi] = useState(0)
  const [currentBmiStatus, setCurrentBmiStatus] = useState('')
  const [showAllDiet, setShowAllDiet] = useState(false)
  const [showAllExercise, setShowAllExercise] = useState(false)
  const [currentTheme, setCurrentTheme] = useState('mint')
  const [results, setResults] = useState({
    bmi: 0,
    bmr: 0,
    bodyFat: 0,
    bmiStatus: '',
    bmiStatusClass: '',
    healthAdvice: {},
    healthAdviceCategory: ''
  })
  const [showToast, setShowToast] = useState(false)
  const [toastMessage, setToastMessage] = useState('')

  // 初始化时获取主题
  useEffect(() => {
    const theme = getCurrentTheme()
    setCurrentTheme(theme)

    // 定时检查主题变化
    const updateTheme = () => {
      const newTheme = getCurrentTheme()
      if (newTheme !== currentTheme) {
        setCurrentTheme(newTheme)
      }
    }

    const interval = setInterval(updateTheme, 5000)
    return () => clearInterval(interval)
  }, [currentTheme])

  // 分享给朋友
  useShareAppMessage(() => {
    return {
      title: '快来测算你的健康指数！科学减脂增肌，定制专属健康方案💪',
      path: '/pages-bmi/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png'
    }
  })

  // 分享到朋友圈
  useShareTimeline(() => {
    return {
      title: '快来测算你的健康指数！科学减脂增肌，定制专属健康方案💪',
      query: '',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/share-img.png'
    }
  })

  // 处理输入变化并计算实时BMI
  const handleInputChange = (field, e) => {
    const value = e.detail.value

    if (field === 'age') {
      if (value === '' || (parseInt(value) >= 10 && parseInt(value) <= 99)) {
        setAge(value)
      }
    } else if (field === 'height') {
      if (value === '') {
        setHeight('')
      } else {
        const heightVal = parseFloat(value)
        if (!Number.isNaN(heightVal)) {
          setHeight(value)
        }
      }
    } else if (field === 'weight') {
      if (value === '' || (parseFloat(value) >= 30 && parseFloat(value) <= 200)) {
        setWeight(value)
      }
    }
  }

  // 实时计算BMI
  useEffect(() => {
    if (height && weight) {
      const heightInMeters = parseFloat(height) / 100
      const weightVal = parseFloat(weight)
      const bmi = weightVal / (heightInMeters * heightInMeters)
      setCurrentBmi(bmi)
      setCurrentBmiStatus(getBMIStatus(bmi))
    } else {
      setCurrentBmi(0)
      setCurrentBmiStatus('')
    }
  }, [height, weight])

  // 计算BMI
  const calculateBMI = (weightVal, heightVal) => {
    const heightInMeters = heightVal / 100
    return weightVal / (heightInMeters * heightInMeters)
  }

  // 获取BMI状态
  const getBMIStatus = (bmi) => {
    if (bmi < 18.5) return '偏瘦'
    if (bmi >= 18.5 && bmi < 24) return '正常'
    if (bmi >= 24 && bmi < 28) return '超重'
    return '肥胖'
  }

  // 获取BMI状态分类（用于查找健身建议）
  const getBMIAdviceCategory = (bmi) => {
    if (bmi < 18.5) return 'Underweight'
    if (bmi >= 18.5 && bmi < 25) return 'Normal'
    if (bmi >= 25 && bmi < 30) return 'Overweight'
    return 'Obese'
  }

  // 获取BMI状态对应的CSS类名
  const getBMIStatusClass = (status) => {
    switch (status) {
      case '偏瘦':
        return 'result-status-thin'
      case '正常':
        return 'result-status-normal'
      case '超重':
        return 'result-status-overweight'
      case '肥胖':
        return 'result-status-obese'
      default:
        return ''
    }
  }

  // 获取BMI状态对应的颜色
  const getBMIStatusColor = (status) => {
    switch (status) {
      case '偏瘦':
        return '#3498db'
      case '正常':
        return '#2ecc71'
      case '超重':
        return '#f39c12'
      case '肥胖':
        return '#e74c3c'
      default:
        return '#95a5a6'
    }
  }

  // 计算BMR (基础代谢率)
  const calculateBMR = (weightVal, heightVal, ageVal, genderVal) => {
    if (genderVal === 'male') {
      return 10 * weightVal + 6.25 * heightVal - 5 * ageVal + 5
    } else {
      return 10 * weightVal + 6.25 * heightVal - 5 * ageVal - 161
    }
  }

  // 计算体脂率
  const calculateBodyFat = (bmi, ageVal, genderVal) => {
    const genderCoefficient = genderVal === 'male' ? 1 : 0
    return 1.2 * bmi + 0.23 * ageVal - 5.4 - 10.8 * genderCoefficient
  }

  // 获取正常体脂率范围
  const getNormalBodyFatRange = (ageVal, genderVal) => {
    if (genderVal === 'male') {
      if (parseInt(ageVal) < 30) return '8-19%'
      else if (parseInt(ageVal) < 50) return '11-21%'
      else return '13-24%'
    } else {
      if (parseInt(ageVal) < 30) return '19-24%'
      else if (parseInt(ageVal) < 50) return '21-27%'
      else return '24-30%'
    }
  }

  // 计算所有结果
  const calculateResults = () => {
    // 验证输入
    if (!age || !height || !weight) {
      setToastMessage('请填写所有必填项')
      setShowToast(true)
      return
    }

    const ageNum = parseInt(age)
    const heightNum = parseFloat(height)
    const weightNum = parseFloat(weight)

    // 计算各项指标
    const bmi = calculateBMI(weightNum, heightNum)
    const bmiStatus = getBMIStatus(bmi)
    const bmiStatusClass = getBMIStatusClass(bmiStatus)
    const bmiAdviceCategory = getBMIAdviceCategory(bmi)
    const bmr = calculateBMR(weightNum, heightNum, ageNum, gender)
    const bodyFat = calculateBodyFat(bmi, ageNum, gender)
    const normalBodyFatRange = getNormalBodyFatRange(ageNum, gender)

    // 设置结果
    setResults({
      bmi: bmi.toFixed(2),
      bmr: Math.round(bmr),
      bodyFat: bodyFat.toFixed(2),
      bmiStatus,
      bmiStatusClass,
      healthAdvice: healthAdviceData[bmiAdviceCategory],
      healthAdviceCategory: bmiAdviceCategory,
      normalBodyFatRange
    })

    setShowResults(true)
  }

  // 返回输入页面
  const goBack = () => {
    setShowResults(false)
    setShowAllDiet(false)
    setShowAllExercise(false)
  }

  // 获取BMI环形进度的百分比
  const getBMICirclePercentage = (bmi) => {
    const bmiNum = parseFloat(bmi)
    let percentage = 0

    if (bmiNum <= 40) {
      percentage = (bmiNum / 40) * 100
    } else {
      percentage = 100
    }

    return percentage
  }

  // 获取BMI环形的颜色
  const getBMICircleColor = (bmi) => {
    const bmiNum = parseFloat(bmi)
    if (bmiNum < 18.5) return '#3498db'
    if (bmiNum < 24) return '#2ecc71'
    if (bmiNum < 28) return '#f39c12'
    return '#e74c3c'
  }

  // 渲染BMI分类条
  const renderBMIClassification = () => {
    const segments = [
      { status: '偏瘦', color: '#3498db', width: 25, range: '< 18.5' },
      { status: '正常', color: '#2ecc71', width: 25, range: '18.5-23.9' },
      { status: '超重', color: '#f39c12', width: 25, range: '24-27.9' },
      { status: '肥胖', color: '#e74c3c', width: 25, range: '≥ 28' }
    ]

    return (
      <View className='bmi-classification'>
        <View className='classification-bar'>
          {segments.map((segment, index) => (
            <View
              key={index}
              className={`segment ${results.bmiStatus === segment.status ? 'active' : ''}`}
              style={{ width: `${segment.width}%`, backgroundColor: segment.color }}
            />
          ))}
        </View>
        <View className='classification-labels'>
          {segments.map((segment, index) => (
            <View key={index} className='label' style={{ width: `${segment.width}%` }}>
              <Text className='value'>{segment.range}</Text>
              <Text className='status'>{segment.status}</Text>
            </View>
          ))}
        </View>
      </View>
    )
  }

  // 渲染健康建议的食谱部分
  const renderDietAdvice = () => {
    const { diet } = results.healthAdvice
    return (
      <View className='advice-section'>
        <View className='advice-header' onClick={() => setShowAllDiet(!showAllDiet)}>
          <Text className='title'>饮食建议</Text>
          {showAllDiet ? <ArrowUp /> : <ArrowDown />}
        </View>
        <View className='advice-content'>
          {diet &&
            (showAllDiet ? diet : diet.slice(0, 1)).map((item, index) => (
              <View key={index} className='advice-item'>
                <Text className='item-number'>{index + 1}</Text>
                <Text className='item-text'>{item}</Text>
              </View>
            ))}
          {diet && diet.length > 1 && !showAllDiet && (
            <Text className='show-more' onClick={() => setShowAllDiet(true)}>
              查看全部
            </Text>
          )}
        </View>
      </View>
    )
  }

  // 渲染健康建议的运动部分
  const renderExerciseAdvice = () => {
    const { exercise, weeklyActivity, notes } = results.healthAdvice
    return (
      <View className='advice-section'>
        <View className='advice-header' onClick={() => setShowAllExercise(!showAllExercise)}>
          <Text className='title'>运动建议</Text>
          {showAllExercise ? <ArrowUp /> : <ArrowDown />}
        </View>
        <View className='advice-content'>
          {exercise &&
            (showAllExercise ? exercise : exercise.slice(0, 1)).map((item, index) => (
              <View key={index} className='advice-item'>
                <Text className='item-number'>{index + 1}</Text>
                <Text className='item-text'>{item}</Text>
              </View>
            ))}

          {showAllExercise && weeklyActivity && (
            <View className='advice-item'>
              <Text className='item-subtitle'>周活动量：</Text>
              <Text className='item-text'>{weeklyActivity}</Text>
            </View>
          )}

          {showAllExercise && notes && (
            <View className='advice-item'>
              <Text className='item-subtitle'>注意事项：</Text>
              <Text className='item-text'>{notes}</Text>
            </View>
          )}

          {exercise && exercise.length > 0 && !showAllExercise && (
            <Text className='show-more' onClick={() => setShowAllExercise(true)}>
              查看全部
            </Text>
          )}
        </View>
      </View>
    )
  }

  return (
    <View className={`bmi-calculator theme-${currentTheme}`}>
      <Toast open={showToast} onClose={() => setShowToast(false)}>
        {toastMessage}
      </Toast>

      {!showResults ? (
        <View className='input-section'>
          <View className='page-title-container'>
            <Text className='page-title'>身体健康指标计算</Text>
            <View className='title-underline'></View>
          </View>

          {/* Share Button */}
          <Button open-type='share' className='share-button'>
            <Share size='24' color='#fff' />
            <Text className='share-text'>分享</Text>
          </Button>

          <View className='input-form'>
            <View className='gender-section'>
              <Text className='section-label'>性别</Text>
              <View className='gender-buttons'>
                <View
                  className={`gender-button ${gender === 'male' ? 'active' : ''}`}
                  onClick={() => setGender('male')}>
                  <Text className='gender-text'>男</Text>
                </View>
                <View
                  className={`gender-button ${gender === 'female' ? 'active' : ''}`}
                  onClick={() => setGender('female')}>
                  <Text className='gender-text'>女</Text>
                </View>
              </View>
            </View>

            <View className='input-fields'>
              <View className='input-field-container'>
                <Input
                  className='input-field'
                  type='number'
                  placeholder='年龄'
                  value={age}
                  onInput={(e) => handleInputChange('age', e)}
                />
                <Text className='input-range'>10-99岁</Text>
              </View>

              <View className='input-field-container'>
                <Input
                  className='input-field'
                  type='digit'
                  placeholder='身高'
                  value={height}
                  onInput={(e) => handleInputChange('height', e)}
                />
                <Text className='input-range'>100-220cm</Text>
              </View>

              <View className='input-field-container'>
                <Input
                  className='input-field'
                  type='digit'
                  placeholder='体重'
                  value={weight}
                  onInput={(e) => handleInputChange('weight', e)}
                />
                <Text className='input-range'>30-200kg</Text>
              </View>
            </View>

            {currentBmi > 0 && (
              <View className='realtime-preview'>
                <View className='bmi-circle-container'>
                  <View
                    className='bmi-circle'
                    style={{
                      background: `conic-gradient(${getBMICircleColor(currentBmi)} ${getBMICirclePercentage(
                        currentBmi
                      )}%, transparent 0)`
                    }}>
                    <View className='bmi-circle-inner'>
                      <Text className='bmi-value'>{currentBmi.toFixed(1)}</Text>
                      <Text className='bmi-label'>BMI</Text>
                    </View>
                  </View>
                </View>
                <Text className='bmi-status' style={{ color: getBMIStatusColor(currentBmiStatus) }}>
                  {currentBmiStatus}
                </Text>
                <Text className='bmi-reference'>World Health Organization (WHO)</Text>
              </View>
            )}

            <Button className='calculate-btn' onClick={calculateResults}>
              立即测算
            </Button>

            <View className='ad-space'>{/* 广告空间 */}</View>
          </View>
        </View>
      ) : (
        <View className='results-section'>
          <View className='page-title-container'>
            <Text className='page-title'>健康指标测算结果</Text>
            <View className='title-underline'></View>
          </View>

          {/* Share Button */}
          <Button open-type='share' className='share-button'>
            <Share size='24' color='#fff' />
            <Text className='share-text'>分享</Text>
          </Button>

          <View className='bmi-result-circle-container'>
            <View
              className='bmi-result-circle'
              style={{
                background: `conic-gradient(${getBMICircleColor(results.bmi)} ${getBMICirclePercentage(
                  results.bmi
                )}%, transparent 0)`
              }}>
              <View className='bmi-result-circle-inner'>
                <Text className='bmi-result-value'>{results.bmi}</Text>
                <Text className='bmi-result-label'>BMI</Text>
              </View>
            </View>
            <Text className='bmi-result-status' style={{ color: getBMIStatusColor(results.bmiStatus) }}>
              {results.bmiStatus}
            </Text>
          </View>

          {renderBMIClassification()}

          <View className='metrics-cards'>
            <View className='metric-card'>
              <Text className='metric-title'>BMI 指数</Text>
              <View className='metric-content'>
                <Text className='metric-value'>{results.bmi}</Text>
                <Text className='metric-status' style={{ backgroundColor: getBMIStatusColor(results.bmiStatus) }}>
                  {results.bmiStatus}
                </Text>
              </View>
            </View>

            <View className='metric-card'>
              <Text className='metric-title'>基础代谢率</Text>
              <View className='metric-content'>
                <Text className='metric-value'>{results.bmr}</Text>
                <Text className='metric-unit'>kcal/天</Text>
              </View>
              <Text className='metric-description'>每日最低热量需求</Text>
            </View>

            <View className='metric-card'>
              <Text className='metric-title'>体脂率(估算)</Text>
              <View className='metric-content'>
                <Text className='metric-value'>{results.bodyFat}%</Text>
              </View>
              <Text className='metric-description'>正常范围: {results.normalBodyFatRange}</Text>
            </View>
          </View>

          <View className='advice-container'>
            <Text className='advice-title'>健身减肥建议</Text>
            <Text className='advice-description'>{results.healthAdvice.description}</Text>

            {renderDietAdvice()}
            {renderExerciseAdvice()}
          </View>

          <Button className='back-btn' onClick={goBack}>
            返回修改
          </Button>
        </View>
      )}
    </View>
  )
}

export default BmiCalculator
